import sys
import types
from ats.cache import memcache_mgr 


# -----------------------------------------------------------------------------
# Global
# -----------------------------------------------------------------------------
cache = memcache_mgr.get_cache()

# -----------------------------------------------------------------------------
# Decorator functions
# -----------------------------------------------------------------------------
def page_cache(min=5):
	""" This decorator will cache the output of a page for 'min' minutes.
			It is setup to handle the various return vals of an ats handler.

			I originally saw a caching decorator in django which is where I got
			the idea so credit goes to the django team for this one.

			usage:
				@page_cache(20)
				def handler(req, sesh):
					return "this guy is cached for 20 minutes"
	"""
	def _rapper(f):
		def __rapper(*args, **kw):
			global cache 
			k = "pc:%d" %(hash(args.__str__()+kw.__str__()))
			result = cache.get(k)
			if result:
				return result 
			result = f(*args, **kw)
			if type(result) is not types.TupleType:
				cache.set(k, str(result), min*60)
			elif len(result) == 3:
				cache.set(k,(result[0], result[1], str(result[2])), min*60)
			elif len(result) == 2:
				cache.set(k,(result[0], str(result[1])), min*60)
			else:
				cache.set(k,(str(result[0]),), min*60)
			return result
		return __rapper
	return _rapper
